package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ? ")
//    @Scheduled(cron = "0/10 * * * * ? ")
    public void processTimeOutOrder() {
        log.info( "超时订单定时处理:{}", LocalDateTime.now() );
        LocalDateTime time = LocalDateTime.now().plusMinutes( -15 );
        List<Orders> list = orderMapper.getByStatusAndTime( Orders.PENDING_PAYMENT, time );
        if (list != null && list.size() > 0) {
            list.forEach( l -> {
                l.setStatus( Orders.CANCELLED );
                l.setCancelReason( "订单超时,自动取消" );
                l.setCancelTime( LocalDateTime.now() );
                orderMapper.update( l );
            } );
        }
    }

    /**
     * 处理派送中实际已经完成的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
//    @Scheduled(cron = "1/10 * * * * ? ")
    public void processDeliveryOrder() {
        log.info( "派送中订单定时处理；{}", LocalDateTime.now() );
        LocalDateTime time = LocalDateTime.now().plusMinutes( -60 );
        List<Orders> ordersList = orderMapper.getByStatusAndTime( Orders.DELIVERY_IN_PROGRESS, time );
        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach( l -> {
                l.setStatus( Orders.COMPLETED );
                orderMapper.update( l );
            } );
        }
    }
}
